const express = require('express');
const router = express.Router();
const { Articles, Likes, Users} = require('../models');
const { success, failure } = require('../utils/responses');
const { NotFoundError } = require('../utils/errors');

/**
 * 点赞、取消赞
 * POST /likes
 */
router.post('/', async function (req, res) {
    try {
        const userid = req.userId;
        const { id } = req.body;

        const articles = await Articles.findByPk(id);
        if (!articles) {
            throw new NotFoundError('文章不存在。');
        }
        // 检查课程之前是否已经点赞
        const like = await Likes.findOne({
            where: {
                userid,
                postid:id
            }
        });
        // // 如果没有点赞过，那就新增。并且文章的 likesCount + 1
        if (!like) {
            await Likes.create({ postid: id, userid });
            await articles.increment('likesCount');
            success(res, '点赞成功。')
        } else {
            // 如果点赞过了，那就删除。并且文章的 likesCount - 1
            await like.destroy();
            await articles.decrement('likesCount');
            success(res, '取消赞成功。')
        }

        res.json()


    } catch (error) {
        failure(res, error);
    }
});
// 查询当前用户点赞过的文章
router.get('/', async function (req, res) {
    try {
        // 通过文章查询点赞的用户
        const query = req.query;
        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;
        const user = await Users.findByPk(req.userId);

        const courses = await user.getLikeArticles({
            joinTableAttributes: [],
            attributes: { exclude: ['id', 'UserId', 'content'] },
            order: [['id', 'DESC']],
            limit: pageSize,
            offset: offset
        });    
        // 查询当前用户点赞过的文章总数
        const count = await user.countLikeArticles();

        success(res, '查询用户点赞的课程成功。', {
            courses,
            pagination: {
                total: count,
                currentPage,
                pageSize,
            }
        });


    } catch (error) {
        failure(res, error); // 处理异常情况
    }
});
// 查询文章获赞详细。
router.get('/:id', async function (req, res) {
    try {
        const query = req.query;
        const postid  =req.params.id

        const currentPage = Math.abs(Number(query.currentPage)) || 1;
        const pageSize = Math.abs(Number(query.pageSize)) || 10;
        const offset = (currentPage - 1) * pageSize;
        const likes = await Articles.findByPk(postid, {
            include: {
                model: Users,
                as: 'likeUsers'
            }
        });
        // 查询当前用户点赞过的课程
        // 查询当前用户点赞过的课程总数
        success(res, '查询文章获赞详细成功。', {
            data:likes,
            pagination: {
                currentPage,
                pageSize,
            }
        });


    } catch (error) {
        failure(res, error); // 处理异常情况
    }
});
module.exports = router;
